package project.ccso.top.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import project.ccso.top.bean.ReturnResult;
import project.ccso.top.entity.Admin;
import project.ccso.top.enumerate.Result;
import project.ccso.top.service.AdminService;
import project.ccso.top.service.impl.AdminServiceImpl;

/**
 * AdminServlet
 * 处理与Admin相关的请求
 * @author aibinxiao
 * @date 2018年8月23日 上午10:46:01
 */
@WebServlet("/AdminServlet")
public class AdminServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private static int cookieExpireTime = 120*24*60*60;
	private static Logger logger = LoggerFactory.getLogger(AdminServlet.class);
	private AdminService adminService = new AdminServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		HttpSession session = request.getSession();
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		ReturnResult result = new ReturnResult();
		Admin existAdmin = null;
		try {
			existAdmin = adminService.login(loginName, password);
			result.setResult(Result.SUCCESS.name());
			result.setMessage("管理员登录成功！");
			logger.info(result.getMessage());
		} catch (Exception e) {
			result.setResult(Result.FAILED.name());
			result.setMessage("管理员登录失败！");
			e.printStackTrace();
			logger.error(result.getMessage());
		}
		result.setData(existAdmin);
		// 判断
		if (existAdmin != null) {
			session.setAttribute("existAdmin", existAdmin);
			// 写入到cookie
			Cookie cookie = new Cookie("adminId", existAdmin.getId().toString());
            cookie.setMaxAge(cookieExpireTime);
            cookie.setPath("/");
            response.addCookie(cookie);
		}
		writer.print(mapper.writeValueAsString(result));
	}
}
